<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 第三方登录
 *
 * @author      Eden
 * @datetime    2016/12/8 21:22
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Social_Model extends API_Model
{
    /**
     * 绑定的会员ID
     * @var int
     */
    private $bindUserId = 0;

    /**
     * 参数
     * @var array
     */
    private $params = array();

    /**
     * 登录信息
     * @var array
     */
    private $userSocial = array();

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 主程序
     * @param array $params
     */
    public function run($params = array())
    {
        $this->params = $params;
        $send['state'] = false;
        do {

            $this->_checkParams();
            // 检查 是否已绑定
            if ($this->_checkBind()) {
                if ($userInfo = $this->_getUserInfo()) {

                    // 修改最后登录信息
                    $this->_modifyLoginInfo();

                    $send['state'] = true;
                    $send['data'] = array(
                        'isBind' => true,
                        'data' => $userInfo
                    );

                    @statIncr('appUsers');
                } else {
                    $send['error'] = '用户未绑定';
                }
            } else {
                // 未绑定
                $send['state'] = true;
                $send['data'] = array(
                    'isBind' => false,
                    'data' => new stdClass()
                );
            }
        } while(false);
        $this->output->send($send);
    }

    private function _modifyLoginInfo()
    {
        // 修改user表
        $db = clone($this->db);
        $db->update('user', array('lastIp' => remoteAddr(), 'lastTime' => dateTime()));

        // 修改user_login表
        $loginDb = clone($this->db);
        $query = $loginDb->get_where('user_mobile_login',
            array('userId' => $this->bindUserId, 'deviceId' => $this->params['deviceId']));
        $row = $query->row_array();
        if ($row) {
            $this->db->update('user_mobile_login', array(
                'type' => $this->params['type'],
                'loginTime' => dateTime()
            ));
        } else {
            $this->db->insert('user_mobile_login', array(
                'userId' => $this->bindUserId,
                'deviceId' => $this->params['deviceId'],
                'type' => $this->params['type'],
                'loginTime' => dateTime()
            ));
        }
    }

    /**
     * 获取用户信息
     * @return array
     */
    private function _getUserInfo()
    {
        $db = clone($this->db);
        $query = $db->select('u.id, u.phone, u.nickName, u.status, u.lastIp, u.lastTime, u.userType, ud.avatar, ud.trueName')
            ->join('user_profile as ud', 'ud.userId = u.id')
            ->where('u.id', $this->bindUserId)
            ->from('user as u')
            ->get();
        $row = $query->row_array();
        if ($row) {

            if ($row['status'] == 0) {
                $this->output->send(array(
                    'state' => false,
                    'error' => '用户被限制登录'
                ));
                exit;
            }

            // get purchaser apply
            $db2 = clone($this->db);
            $q = $db2->get_where('purchaser_apply', ['userId' => $this->bindUserId]);
            $item = $q->row_array();
            if (empty($item)) {
                $purchaser = 0;
            } else if($item['status'] == 6) {
                $purchaser = 6;
            } else if($item['status'] == 0) {
                $purchaser = 3;
            } else {
                $purchaser = 5;
            }


            return array(
                'userId' => intval($row['id']),
                'nickName' => $row['nickName'],
                'trueName' => $row['trueName'],
                'phone' => $row['phone'],
                'avatar' => thumb($row['avatar'], 100, 100),
                'lastIp' => $row['lastIp'],
                'lastTime' => $row['lastTime'],
                'status' => intval($row['status']),
                'purchaser' => intval($purchaser)
            );
        } else {
            $this->output->send(array(
                'state' => false,
                'error' => '服务器错误'
            ));
        }
    }

    /**
     * 检查是否绑定
     * @return bool
     */
    private function _checkBind()
    {
        $socialDb = clone($this->db);
        try {
            $query = $socialDb->get_where('user_social', array('openId' => $this->params['openId']));
            $row = $query->row_array();
            if ($row) {
                $this->userSocial = $row;
                if ($row['userId'] == 0) {
                    return false;
                } else {
                    $this->bindUserId = $row['userId'];
                    return true;
                }
            } else {
                // 插入
                $data = array(
                    'userId' => 0,
                    'nickName' => $this->params['nickName'],
                    'figureUrl' => $this->params['figureUrl'],
                    'gender' => $this->params['gender'],
                    'platform' => $this->params['platform'],
                    'openId' => $this->params['openId'],
                    'device' => 'phone',
                    'created' => dateTime(),
                    'deviceId' => $this->params['deviceId']
                );
                $socialDb->insert('user_social', $data);
                $this->userSocial = $data;
                return false;
            }

        } catch(PDOException $e) {
            $this->output->send(array(
                'state' => false,
                'error' => '服务器错误'
            ));
        }
    }

    /**
     * 检查参数
     * @return bool
     */
    private function _checkParams()
    {
        $send['state'] = false;
        do {

            if ($this->input->method(true) !== 'POST') {
                $send['error'] = '非法请求';
                break;
            }

            $params = $this->params;
            if (empty($params['platform']) || empty($params['nickName']) || empty($params['openId'])
                || empty($params['figureUrl']) || empty($params['deviceId'])) {
                $send['error'] = '缺少必填参数';
                break;
            }

            if (empty($params['gender'])) {
                $params['gender'] = '男';
            }

            if (!in_array($params['gender'], array('男', '女'))) {
                $params['gender'] = '男';
            }

            if (isset($params['platform'])) {
                $params['platform'] = strtolower($params['platform']);
            }

            if (!in_array($params['platform'], array('qq', 'wechat'))) {
                $send['error'] = '暂不支持此平台登录';
                break;
            }
            $this->params = $params;
            return true;
        } while(false);
        $this->output->send($send);
    }

}
